<template>
    <div class="ruifox-files-upload">
        <el-dialog
            v-model="showDialog"
            @close="handleClose"
            title="附件上传"
            width="960px"
            class="filesupload-box"
        >
            <div class="inner-filesupload-box">
                <div class="files-upload-box">
                    <!-- 本地上传 -->
                    <div class="local-upload">
                        <el-upload
                            ref="uploadRef"
                            v-model:file-list="filesUploadList"
                            class="upload-demo"
                            action=""
                            multiple
                            :show-file-list="false"
                            :before-upload="handleBeforeUpload"
                            :http-request="handleUpload"
                            :limit="limit - filesUploadList.length"
                            accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt,.rar,.zip"
                        >
                            <template #trigger>
                                <el-button type="primary" style="margin-bottom: 10px">上传附件</el-button>
                            </template>
                            <template #default>
                                <div style="display: inline-flex;margin-left: 10px;">
                                    <el-button @click="handleMaterial">从资料库选择</el-button>
                                </div>
                                <div class="local-upload-list-out">
                                    <el-scrollbar height="400px">
                                        <draggable
                                            :list="filesUploadList"
                                            animation="180"
                                            item-key="uid"
                                            :force-fallback="true"
                                            class="local-upload-list"
                                        >
                                            <template #item="{ element }">
                                                <div>
                                                    <li>
                                                        <div class="file-box">
                                                            <i></i>
                                                            <p class="tit">{{element.name}}</p>
                                                        </div>
                                                        <div class="progress-box" v-show="element.percentage !== 100">
                                                            <el-progress :percentage="element.percentage" :status="element.status === 'success' ? 'success' : ''" :stroke-width="20" :text-inside="true"/>
                                                        </div>
                                                        <div class="remove-upload" @click.stop="removeUpload(element.uid)">
                                                            <el-icon><Delete /></el-icon>
                                                        </div>
                                                    </li>
                                                </div>
                                            </template>
                                        </draggable>
                                    </el-scrollbar>
                                </div>
                            </template>
                        </el-upload>
                    </div>
                    <!-- 从资料库选择 -->
                    <el-dialog
                        v-model="materialShow"
                        width="960px"
                        title="从资源库选择"
                        @close="handleMaterialClose"
                    >
                        <div class="online-upload">
                            <div class="online-upload-list-outer">
                              <el-scrollbar height="360px">
                                <div class="online-upload-list">
                                  <div class="online-upload-item" :class="{'is-choose':  choseFilesList.find(a => a.id === item.id)}" v-for="item in materialFiles" :key="item.id" @click="toggleChooseOnline(item)">
                                        <div class="upload-item-checkbox">
                                            <el-icon><Check /></el-icon>
                                        </div>
                                        <div class="file-box" :class="getFileType(item.name)">
                                            <p class="tit">{{item.name}}</p>
                                        </div>
                                  </div>
                                </div>
                              </el-scrollbar>
                            </div>
                            <div class="chose-file">
                              <div class="chose-file-title">
                                <p>从资源库中选择附件</p>
                                <p>已选：<span>{{choseFilesList.length}}</span></p>
                              </div>
                              <div class="material-chose-list">
                                <div >
                                  <el-scrollbar >
                                    <div class="inner-material-chose-list">
                                      <li class="material-chose-list-item" v-for="item in choseFilesList" :key="item.id">
                                        <div class="file-box">
                                            <p class="tit" :class="getFileType(item.name)">{{item.name}}</p>
                                        </div>
                                        <div class="remove-btn" @click.stop="removeChose(item.id)">
                                          <el-icon><Delete /></el-icon>
                                        </div>
                                      </li>
                                    </div>
                                  </el-scrollbar>
                                </div>
                              </div>
                            </div>
                          </div>
                          <template #footer>
                            <span class="dialog-footer">
                            <el-button type="primary" @click="addMaterialFile">
                              确认
                            </el-button>
                            <el-button @click="materialShow = false">取消</el-button>
                          </span>
                          </template>
                    </el-dialog>
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="insertFiles">
                    确认
                    </el-button>
                    <el-button @click="closeDialog">取消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, watch} from 'vue';
import draggable from "vuedraggable";
import {getFilesMaterial} from "@/api/content";
import { Check, Delete } from '@element-plus/icons-vue'
import {useStore} from "vuex";
import {fileMd5, singleUpload, splitUpload} from "@/utils/upload";
const store = useStore()

const props = defineProps({
  //打开dialog
  showDialog: {
    type: Boolean,
    default: false
  },
  limit: {
    type: Number,
    default: null
  }
})
const showDialog = ref(props.showDialog)
const limit = ref(props.limit)
watch(props,(newVal) => {
  showDialog.value = newVal.showDialog
},{deep: true})

const emit = defineEmits(['update:showDialog','getFileList'])
const handleClose = () => {
  emit('update:showDialog',false)
}
const closeDialog = () => {
  emit('update:showDialog',false)
}
const actionUrl = ref(store.state.content.uploadUrl)
store.dispatch('content/updateUploadUrl').then(res => {
  actionUrl.value = res.uploadUrl
})
//上传附件
const filesUploadList = ref([])
//删除
const removeUpload = (id) => {
    filesUploadList.value = filesUploadList.value.filter(item => item.uid !== id)
}
const handleBeforeUpload = async (file) => {
  let res = await fileMd5(file,actionUrl.value)
  if(res.data.length === 0){
    return true
  }else{
    filesUploadList.value.push({
      uid: file.uid,
      percentage: 100,
      url: res.data.url,
      name: file.name,
      id: file.uid,
      status: 'success'
    })
    return false
  }
}
const handleUpload = async (option) => {
  if (option.file.size > 5 * 1024 * 1024) {
    let res = await splitUpload(option.file, actionUrl.value ,option.onProgress , 5 * 1024 * 1024)
    console.log(res)
    handleUploadSuccess(res.data,option.file)
  } else {
    // 不切片
    let data = new FormData()
    data.append('file', option.file)
    data.append('name', option.file.name)
    data.append('size', option.file.size)
    data.append('lastModifiedDate', option.file.lastModifiedDate)
    let res = await singleUpload(data, actionUrl.value, option.onProgress)
    handleUploadSuccess(res.data,option.file)
  }
}
const handleUploadSuccess = (res,file) => {
  console.log(res,file)
  file.url = res.url
  file.id = file.uid
}

const materialShow = ref(false) //资源库弹框
const materialFiles = ref([])
const handleMaterial = () => {
  materialShow.value = true
  //获取数据
  getFilesMaterial().then(res => {
    materialFiles.value = res.data
  })
}
const choseFilesList = ref([])
const toggleChooseOnline = (item) => {
  if(choseFilesList.value.find(a => a.id === item.id)){
    choseFilesList.value = choseFilesList.value.filter(a => a.id !== item.id)
  }else{
      if(choseFilesList.value.length < limit.value - filesUploadList.value.length){
        item.percentage = 100
        item.uid = item.id
        choseFilesList.value.push(item)
      }else{
        return
      }
  }

}
const removeChose = (id) => {
    choseFilesList.value = choseFilesList.value.filter(item => item.id !== id)
}
// 资源库附件添加
const addMaterialFile = () => {
    filesUploadList.value = filesUploadList.value.concat(choseFilesList.value)
    let obj = {};
    filesUploadList.value = filesUploadList.value.reduce((cur, next) => {
        obj[next.id] ? '' : obj[next.id] = true && cur.push(next);
        return cur
    }, []);
    materialShow.value = false
}
// 关闭资源库弹框触发
const handleMaterialClose = () => {
    choseFilesList.value = []
}

const uploadRef = ref()
const insertFiles = () => {
  console.log(filesUploadList.value)
  let _fileList = filesUploadList.value.map(item => {
    let _item = {
      id: item.id,
      name:item.name,
      url: item.url
    }
    if(item.raw) {_item.id = item.raw.uid;_item.url = item.raw.url;_item.name=item.raw.name}
    return _item
  })
  uploadRef.value.clearFiles()
  emit('getFileList',_fileList)
  choseFilesList.value = []
  emit('update:showDialog',false)
}

const getFileType = (name) => {
    return name.substring(name.lastIndexOf('.') + 1)
}
</script>
<style lang="scss" scoped>
::v-deep(.filesupload-box .el-dialog__body){
  padding: 0;
}
.filesupload-box {
    .inner-filesupload-box {
        display: flex;
        height: 480px;
        .files-upload-box {
            height: 100%;
            width: 100%;
            .local-upload{
                padding: 20px;
                .local-upload-list-out{
                    height: 400px;
                    border: 1px solid $borderColor;
                }
                .local-upload-list{
                    height: 400px;
                    position: relative;
                    padding: 20px;
                    box-sizing: border-box;
                    &>div{
                        background-color: #F8F8F8;
                    }
                    li{
                        transition: all 0.3s;
                        box-sizing: border-box;
                        list-style: none;
                        border: 1px solid #E4E4E4;
                        position: relative;
                        cursor: pointer;
                        margin-bottom: 10px;
                        .file-box {
                            padding: 0 5px;
                        }
                        .progress-box{
                            width: 100%;
                            /* position: absolute; */
                            bottom: 0;
                            left:0;
                            ::v-deep(.el-progress-bar__outer){
                                border-radius: 0;
                            }
                            ::v-deep(.el-progress-bar__inner){
                                border-radius: 0;
                            }
                        }
                        .remove-upload{
                            color: $white;
                            position: absolute;
                            right: 5px;
                            top: 3px;
                            cursor: pointer;
                            display: none;
                            height: 24px;
                            width: 24px;
                            background-color: #FF5240;
                            box-sizing: border-box;
                            border: 1px solid rgba(255,255,255,0.5);
                            align-items: center;
                            justify-content: center;
                            i{
                                font-size: 16px;
                            }
                        }
                        &:hover{
                            box-shadow: 0 0 10px rgba(0,0,0,0.2);
                            border-color: $mainColor;
                            background-color: $focusContent;
                            .remove-upload{
                                display: flex;
                            }
                        }
                    }
                }
            }
            .online-upload{
                padding: 20px;
                .online-upload-list-outer{
                    height: 360px;
                    width: 100%;
                    border: 1px solid $borderColor;
                    box-sizing: border-box;
                    padding: 20px;
                }
                .online-upload-list{
                    /* height: 375px; */
                    display: flex;
                    flex-wrap: wrap;
                    .online-upload-item{
                        width: 160px;
                        cursor: pointer;
                        box-sizing: border-box;
                        transition: all 0.3s;
                        position: relative;
                        margin-bottom:10px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        margin-right: 20px;
                        .file-box {
                            position: relative;
                            width: 100%;
                            padding-top: 60px;
                            text-align: center;
                            &:before{
                                position: absolute;
                                top: 5px;
                                font-size: 50px;
                                line-height: 1;
                                content: "\e663";
                                display: block;
                                font-family: "iconfont";
                                left:50%;
                                transform:translateX(-50%)
                            }
                            &.doc:before, &.docx:before{
                                content:"\e806";
                                color:#4099ff;
                            }
                            &.xls:before,&.xlsx:before{
                                content:"\e67a";
                            }
                            &.pdf:before{
                                content:"\e602";
                            }
                            &.zip:before{
                                content:"\e605";
                            }
                        }
                        .upload-item-checkbox{
                            position: absolute;
                            height: 24px;
                            width: 24px;
                            box-sizing: border-box;
                            border: 1px solid #DCDFE6;
                            top: 4px;
                            right: 5px;
                            background-color: $white;
                            display: none;
                            transition: all 0.2s;
                            align-items: center;
                            justify-content: center;
                            i{
                                font-weight: bold;
                                font-size: 18px;
                                color: $white;
                            }
                        }
                        &:nth-child(5n+1){
                            margin-left: 20px;
                        }
                        &.is-choose{
                            border-color: $hoverColor;
                            background-color: $focusContent;
                            .upload-item-checkbox{
                                display: flex;
                                background-color: #2CBF77;
                                border-color: #2CBF77;
                            }
                        }
                        &:hover{
                            background-color: $focusContent;
                            .upload-item-checkbox{
                                display: flex;
                            }
                        }
                    }
                }
                .chose-file{
                    margin-top: 25px;
                    .chose-file-title{
                        display: flex;
                        justify-content: space-between;
                        margin-bottom: 10px;
                        p{
                            span{
                                color: #2CBF77;
                            }
                        }
                    }
                    .material-chose-list{
                        background-color: $focusContent;
                        min-height: 120px;
                        box-sizing: border-box;
                        padding: 10px 40px;
                        .inner-material-chose-list{
                            width: 100%;
                            .material-chose-list-item{
                                transition: all 0.2s;
                                position: relative;
                                background-color: $backBase;
                                border: 1px solid #E4E4E4;
                                flex-shrink: 0;
                                margin-bottom: 10px;
                                .file-box {
                                    padding: 0 5px;
                                    .tit {
                                        position: relative;
                                        padding-left: 30px;
                                        &:before{
                                            position: absolute;
                                            left: 0;
                                            font-size: 22px;
                                            line-height: 1;
                                            content: "\e663";
                                            display: block;
                                            font-family: "iconfont";
                                            top:50%;
                                            transform:translateY(-50%)
                                        }
                                        &.doc:before, &.docx:before{
                                            content:"\edd5";
                                            color:#4568a0;
                                        }
                                        &.xls:before,&.xlsx:before{
                                            content:"\e67a";
                                            color:#378458;
                                        }
                                        &.pdf:before{
                                            content:"\e602";
                                            color:#e81f05;
                                        }
                                        &.zip:before{
                                            content:"\e605";
                                            color:#a372db;
                                        }
                                    }
                                }
                                .remove-btn{
                                    color: $white;
                                    position: absolute;
                                    right: 5px;
                                    top: 5px;
                                    cursor: pointer;
                                    display: none;
                                    height: 24px;
                                    width: 24px;
                                    background-color: #FF5240;
                                    box-sizing: border-box;
                                    border: 1px solid rgba(255,255,255,0.5);
                                    align-items: center;
                                    justify-content: center;
                                    i{
                                        font-size: 16px;
                                    }
                                }
                                &:hover{
                                    background-color: $focusContent;
                                    border-color: $hoverColor;
                                    box-shadow: 0 0 10px rgba(0,0,0,0.2);
                                    .remove-btn{
                                        display: flex;
                                    }
                                }
                                &:nth-last-child(1){
                                    margin-right: 0;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</style>
